package clientserver;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class ServerSocketExample {
	private ServerSocket server;
	private final int port = 8999;

	public ServerSocketExample() {
		try {
			server = new ServerSocket(port);
		} catch (final IOException e) {
			e.printStackTrace();
		}
	}

	public static void main(final String[] args) {
		final ServerSocketExample example = new ServerSocketExample();
		example.handleConnection();
	}

	public void handleConnection() {
		System.out.println("Waiting for client message...");

		//
		// The server do a loop here to accept all connection initiated by the
		// client application.
		//
		while (true) {
			try {
				final Socket socket = server.accept();
				new ConnectionHandler(socket);
			} catch (final IOException e) {
				e.printStackTrace();
			}
		}
	}
}

class ConnectionHandler implements Runnable {
	private final Socket socket;

	public ConnectionHandler(final Socket socket) {
		this.socket = socket;

		final Thread t = new Thread(this);
		t.start();
	}

	@Override
	public void run() {
		try {
			//
			// Read a message sent by client application
			//
			final ObjectInputStream ois = new ObjectInputStream(
					socket.getInputStream());
			final String message = (String) ois.readObject();
			System.out.println("Message Received: " + message);

			//
			// Send a response information to the client application
			//
			final ObjectOutputStream oos = new ObjectOutputStream(
					socket.getOutputStream());
			oos.writeObject("Hi...");

			ois.close();
			oos.close();
			socket.close();

			System.out.println("Waiting for client message...");
		} catch (final IOException e) {
			e.printStackTrace();
		} catch (final ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
}
